let num = 1234567
function toThousands (num) {
  num = num.toString()
  let res = ''
  let count = 0
  for (let i = num.length - 1; i > -1; --i) {
    ++count
    res = num.charAt(i) + res
    if (!(count % 3) && i)  res = ',' + res
  }
  console.log(res)
  return res
}

function toThousands (num) {
  num = num.toString()
  let res = ''
  while (3 < num.length) {
    res = ',' + num.slice(-3) + res
    num = num.slice(0, num.length - 3)
  }
  if (num)  res = num + res
  console.log(res)
  return res
}

toThousands(num)
toThousands(0)